package com.bit.webhttp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpServerV1 {
    private ServerSocket serverSocket = null;

    public HttpServerV1(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true){
            //1.获取连接
            Socket clientSocket = serverSocket.accept();
            //2.处理连接
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    process(clientSocket);
                }
            });
        }
    }
    private void process(Socket clientSocket) {
        //由于HTTP协议是文本协议，所以仍然使用字节流来处理
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))) {
        //下面的操作都严格按照HTTP协议来进行操作
        //1.读取请求并解析
            //a）解析首行，三个部分用空格切分
        String firstLine = bufferedReader.readLine();
        String[] firstLineTokens = firstLine.split(" ");
        String method = firstLineTokens[0];
        String url = firstLineTokens[1];
        String version = firstLineTokens[2];
            //b)解析header，按行读取，然后按冒号空格来分割键值对
            Map<String,String> headers = new HashMap<>();
            String line = "";
            //readLine读取的一行内容会自动去掉换行符
            while ((line = bufferedReader.readLine()) !=null && line.length()!=0){
                //不能使用 : 来分割，像referer字段，里面的内容可能包含：
                String[] headerTokens = line.split(": ");
                headers.put(headerTokens[0],headerTokens[1]);
            }
            //c)解析body
            System.out.printf("%s %s %s\n",method,url,version);
            for(Map.Entry<String,String> entry:headers.entrySet()){
                System.out.println(entry.getKey()+": "+entry.getValue());
            }
            System.out.println();
            //2.根据请求计算响应
            String resp = "";
            if(url.equals("/ok")){
                bufferedWriter.write(version + " 200 OK\n");
                resp = "<h1>hello</h1>";
            }else if(url.equals("/notfound")){
                bufferedWriter.write(version+" 404 Not Found\n");
                resp = "<h1>not found<h1>";
            }else if(url.equals("/seeother")){
                bufferedWriter.write(version+" 303 See Other\n");
                bufferedWriter.write("Location: http://www.sogou.com/");
                resp = "";
            }else{
                bufferedWriter.write(version + " 200 OK\n");
                resp = "<h1>default</h1>";
            }
            //3.把响应写会客户端
            bufferedWriter.write("Content-Type: text/html\n");
            bufferedWriter.write("Content-Length: "+resp.getBytes().length+"\n");
            bufferedWriter.write("\n");
            bufferedWriter.write(resp);
            bufferedWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        HttpServerV1 httpServerV1 = new HttpServerV1(9090);
        httpServerV1.start();
    }
}

